/**
 * Layui 搜索输入框组件
 *
 * @author xiaolai
 * @since 20190510
 *
 */
layui.define(['table', 'jquery', 'form','tree'], function(exports) {
    var $ = layui.$,MOD_NAME = 'btnProp',
        table = layui.table,
        form = layui.form,
        tree = layui.tree;

        var btnProp = function () {}
        btnProp.prototype = {
        render:function(opt){


            var tableDone = opt.table.done || function(){layer.closeAll('loading')};
            var elem=$(opt.dst);
            elem.on('click', function(e) {
                    e.stopPropagation();
                    if($('div.btnProp').length >= 1){
                        return false;
                    }
                    var tableName = "btnProp_table_" + new Date().getTime();
                    var tableBox;
                    var treeId;
                    if(opt.tree){
                        tableBox =[
                            '<div class="x-body btnProp">',
                            '   <div class="layui-row">',
                            '       <div class="layui-col-xs2">',
                            '           <div id="leftTree" class="demo-tree demo-tree-box" style="width: 100%; height: 100%; overflow: auto;"></div>',
                            '       </div>',
                            '   <div class="layui-col-xs10">',
                            '       <div class=" layui-anim layui-anim-upbit" style="width:99%;height:95%;padding: 3px">',
                            '           <div class="propSelectBar">',
                            '               <form id="propSelectForm" class="layui-form" action="" style="display:inline-block;">',
                            '                   <input style="display:inline-block;width:190px;height:30px;vertical-align:middle;margin-right:-1px;border: 1px solid #C9C9C9;" type="text" name="'+opt.searchKey+'" placeholder="'+opt.searchPlaceholder+'" autocomplete="off" class="layui-input">',
                            '                   <button class="layui-btn layui-btn-sm layui-btn-primary tableSelect_btn_search" lay-submit lay-filter="tableSelect_btn_search">',
                            '                       <i class="layui-icon layui-icon-search"></i>',
                            '                   </button>',
                            '               </form>',
                            '              <button style="float:right;" class="layui-btn layui-btn-sm tableSelect_btn_select">选择<span></span></button>',
                            '           </div>',
                            '           <table id="'+tableName+'" lay-filter="'+tableName+'"></table>',
                            '       </div>',
                            '   </div>',
                            '</div>'
                        ].join('');
                    }else{
                         tableBox =[
                            '<div class="btnProp layui-anim layui-anim-upbit" style="width:99%;height:95%;padding: 3px">',
                            '<div class="propSelectBar">',
                            '<form class="layui-form" action="" style="display:inline-block;">',
                            '<input style="display:inline-block;width:190px;height:30px;vertical-align:middle;margin-right:-1px;border: 1px solid #C9C9C9;" type="text" name="'+opt.searchKey+'" placeholder="'+opt.searchPlaceholder+'" autocomplete="off" class="layui-input"><button class="layui-btn layui-btn-sm layui-btn-primary tableSelect_btn_search" lay-submit lay-filter="tableSelect_btn_search"><i class="layui-icon layui-icon-search"></i></button>',
                            '</form>',
                            '<button style="float:right;" class="layui-btn layui-btn-sm tableSelect_btn_select">选择<span></span></button>',
                            '</div>',
                            '<table id="'+tableName+'" lay-filter="'+tableName+'"></table>',
                            '</div>'
                        ].join('');

                    }

                    tableBox = $(tableBox);
                    $('body').append(tableBox);
                    var propConfig={
                        type: 1,
                        area: [($(window).width()*0.5)+'px', ($(window).height() *0.85)+'px'],
                        //shadeClose: false,
                        closeBtn:1,
                        success: $.noop,
                        cancel:$.noop,
                        title:'弹出窗口',
                        content: $(".btnProp"),
                        end:function () {
                            tableBox.remove();
                        }
                    }
                    var index=layer.open($.extend(propConfig,opt.windows));
                    var tableConfig={
                        request: common.layui.table.tableRequest
                        , page: true
                        ,height: ($(window).height() *0.72)+'px'
                        ,cellMinWidth: 80 //全局定义常规单元格的最小宽度，layui 2.2.1 新增
                        ,parseData: common.layui.table.tableParseData
                    }

                    if(opt.tree){
                        common.ajax.post(opt.tree.url, {}, function (resp) {
                            tree.render({
                                elem: '#leftTree'
                                ,data: resp.data
                                ,onlyIconControl:true
                                ,click: function(obj){
                                    treeId=obj.data.id
                                    var formData = $('#propSelectForm').serializeArray();
                                    var data={};
                                    data[formData[0].name]=formData[0].value;
                                    searchTable(data);

                                }
                            });
                        });
                    }
                    //数据缓存
                    var checkedData = [];

                    //渲染TABLE
                    opt.table.elem = "#"+tableName;
                    opt.table.id = tableName;
                    opt.table.done = function(res, curr, count){
                        defaultChecked(res, curr, count);
                        setChecked(res, curr, count);
                        tableDone(res, curr, count);
                    };
                    var tableSelect_table = table.render($.extend(tableConfig,opt.table));

                    //分页选中保存数组
                    table.on('radio('+tableName+')', function(obj){
                        if(opt.checkedKey){
                            checkedData = table.checkStatus(tableName).data
                        }
                        updataButton(table.checkStatus(tableName).data.length)
                    })
                    table.on('checkbox('+tableName+')', function(obj){
                        if(opt.checkedKey){
                            if(obj.checked){
                                for (var i=0;i<table.checkStatus(tableName).data.length;i++){
                                    checkedData.push(table.checkStatus(tableName).data[i])
                                }
                            }else{
                                if(obj.type=='all'){
                                    for (var j=0;j<table.cache[tableName].length;j++) {
                                        for (var i=0;i<checkedData.length;i++){
                                            if(checkedData[i][opt.checkedKey] == table.cache[tableName][j][opt.checkedKey]){
                                                checkedData.splice(i,1)
                                            }
                                        }
                                    }
                                }else{
                                    //因为LAYUI问题，操作到变化全选状态时获取到的obj为空，这里用函数获取未选中的项。
                                    function nu (){
                                        var noCheckedKey = '';
                                        for (var i=0;i<table.cache[tableName].length;i++){
                                            if(!table.cache[tableName][i].LAY_CHECKED){
                                                noCheckedKey = table.cache[tableName][i][opt.checkedKey];
                                            }
                                        }
                                        return noCheckedKey
                                    }
                                    var noCheckedKey = obj.data[opt.checkedKey] || nu();
                                    for (var i=0;i<checkedData.length;i++){
                                        if(checkedData[i][opt.checkedKey] == noCheckedKey){
                                            checkedData.splice(i,1);
                                        }
                                    }
                                }
                            }
                            checkedData = uniqueObjArray(checkedData, opt.checkedKey);
                            updataButton(checkedData.length)
                        }else{
                            updataButton(table.checkStatus(tableName).data.length)
                        }
                    });

                    //渲染表格后选中
                    function setChecked (res, curr, count) {
                        for(var i=0;i<res.data.length;i++){
                            for (var j=0;j<checkedData.length;j++) {
                                if(res.data[i][opt.checkedKey] == checkedData[j][opt.checkedKey]){
                                    res.data[i].LAY_CHECKED = true;
                                    var index= res.data[i]['LAY_TABLE_INDEX'];
                                    var checkbox = $('#'+tableName+'').next().find('tr[data-index=' + index + '] input[type="checkbox"]');
                                    checkbox.prop('checked', true).next().addClass('layui-form-checked');
                                    var radio  = $('#'+tableName+'').next().find('tr[data-index=' + index + '] input[type="radio"]');
                                    radio.prop('checked', true).next().addClass('layui-form-radioed').find("i").html('&#xe643;');
                                }
                            }
                        }
                        var checkStatus = table.checkStatus(tableName);
                        if(checkStatus.isAll){
                            $('#'+tableName+'').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').prop('checked', true);
                            $('#'+tableName+'').next().find('.layui-table-header th[data-field="0"] input[type="checkbox"]').next().addClass('layui-form-checked');
                        }
                        updataButton(checkedData.length)
                    }

                    //写入默认选中值(puash checkedData)
                    function defaultChecked (res, curr, count){
                        if(opt.checkedKey && elem.val()){
                            var selected = elem.val().split(",");
                            for(var i=0;i<res.data.length;i++){
                                for(var j=0;j<selected.length;j++){
                                    if(res.data[i][opt.checkedKey] == selected[j]){
                                        checkedData.push(res.data[i])
                                    }
                                }
                            }
                            checkedData = uniqueObjArray(checkedData, opt.checkedKey);
                        }
                    }

                    //更新选中数量
                    function updataButton (n) {
                        tableBox.find('.tableSelect_btn_select span').html(n==0?'':'('+n+')')
                    }

                    //数组去重
                    function uniqueObjArray(arr, type){
                        var newArr = [];
                        var tArr = [];
                        if(arr.length == 0){
                            return arr;
                        }else{
                            if(type){
                                for(var i=0;i<arr.length;i++){
                                    if(!tArr[arr[i][type]]){
                                        newArr.push(arr[i]);
                                        tArr[arr[i][type]] = true;
                                    }
                                }
                                return newArr;
                            }else{
                                for(var i=0;i<arr.length;i++){
                                    if(!tArr[arr[i]]){
                                        newArr.push(arr[i]);
                                        tArr[arr[i]] = true;
                                    }
                                }
                                return newArr;
                            }
                        }
                    }
                    function searchTable(_data){
                        var data=$.extend(_data.field,opt.table.where);
                        if(opt.tree){
                            data[opt.tree.key]=treeId;
                        }
                        tableSelect_table.reload({
                            where: data,
                            page: {
                                curr: 1
                            }
                        });
                    }

                    //FIX位置
                    //var overHeight = (elem.offset().top + elem.outerHeight() + tableBox.outerHeight() - $(window).scrollTop()) > $(window).height();
                   // var overWidth = (elem.offset().left + tableBox.outerWidth()) > $(window).width();
                   // overHeight && tableBox.css({'top':'auto','bottom':'0px'});
                   // overWidth && tableBox.css({'left':'auto','right':'5px'})

                    //关键词搜索
                    form.on('submit(tableSelect_btn_search)', function(_data){
                        searchTable(_data);
                        return false;
                    });

                    //双击行选中
                    table.on('rowDouble('+tableName+')', function(obj){
                        var checkStatus = {data:[obj.data]};
                        selectDone(checkStatus);
                    })

                    //按钮选中
                    tableBox.find('.tableSelect_btn_select').on('click', function() {
                        var checkStatus = table.checkStatus(tableName);
                        if(checkedData.length > 1){
                            checkStatus.data = checkedData;
                        }
                        selectDone(checkStatus);
                    })

                    //写值回调和关闭
                    function selectDone (checkStatus){
                        //var input=obj.get(opt.layFilter);
                        if(opt.checkedKey){
                            var selected = [];
                            var NEWJSON=[];
                            for(var i=0;i<checkStatus.data.length;i++){
                                selected.push(checkStatus.data[i][opt.checkedKey])
                                NEWJSON.push(checkStatus.data[i][opt.checkedName])
                            }
                            opt.done(checkStatus);
                            //input.val(selected.join(","));
                            //input.next().find('input').val(NEWJSON.join(","));
                        }

                        layer.close(index); //它获取的始终是最新弹出的某个层，值是由layer内部动态递增计算的
                        delete table.cache[tableName];
                        checkedData = [];

                    }
                    /*
                    //点击其他区域关闭
                    $(document).mouseup(function(e){
                        var userSet_con = $(''+opt.elem+',.btnProp');
                        if(!userSet_con.is(e.target) && userSet_con.has(e.target).length === 0){
                            layer.close(layer.index)

                            delete table.cache[tableName];
                            checkedData = [];
                        }
                    });*/
            })
        }
    }
    var i = new btnProp();
    exports(MOD_NAME, i);
});
